//
//  MessageManager.swift
//  Billing
//
//  Created by Dale on 2017/5/9.
//  Copyright © 2017年 Nari. All rights reserved.
//

import UIKit
import UserNotifications

var messageList:[String] = []

class MessageManager: NSObject, GeTuiSdkDelegate, UNUserNotificationCenterDelegate {
    
    //单例
    static var defaultMessageManager : MessageManager {
        struct Static {
            static let instance : MessageManager = MessageManager()
        }
        return Static.instance
    }
    /** 注册用户通知(推送) */
    func registerRemoteNotification() {
        let systemVer = (UIDevice.current.systemVersion as NSString).floatValue;
        if systemVer >= 10.0 {
            if #available(iOS 10.0, *) {
                let center:UNUserNotificationCenter = UNUserNotificationCenter.current()
                center.delegate = self;
                center.requestAuthorization(options: [.alert,.badge,.sound], completionHandler: { (granted:Bool, error:Error?) -> Void in
                    if (granted) {
                        print("注册通知成功") //点击允许
                    } else {
                        print("注册通知失败") //点击不允许
                    }
                })
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
        else if systemVer >= 8.0 {
            if #available(iOS 8.0, *) {
                let userSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
                UIApplication.shared.registerUserNotificationSettings(userSettings)
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    
    func startGeTui() {
        GeTuiSdk.start(withAppId: kGtAppId, appKey: kGtAppKey, appSecret: kGtAppSecret, delegate: self);
        // [ GTSdk ]：使用APPID/APPKEY/APPSECRENT启动个推
        // [ GTSdk ]：是否允许APP后台运行
          GeTuiSdk.runBackgroundEnable(false);
        // [ GTSdk ]：是否运行电子围栏Lbs功能和是否SDK主动请求用户定位
        GeTuiSdk.lbsLocationEnable(true, andUserVerify: true);
    }

    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("willPresentNotification: \(notification.request.content.userInfo)");
        
        completionHandler([.badge,.sound,.alert]);
    }
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        print("didReceiveNotificationResponse:\(response.notification.request.content.userInfo)")
        
        // [ GTSdk ]：将收到的APNs信息传给个推统计
        GeTuiSdk.handleRemoteNotification(response.notification.request.content.userInfo)
        
        completionHandler()
    }

    // MARK: - GeTuiSdkDelegate
    /** SDK启动成功返回cid */
    func geTuiSdkDidRegisterClient(_ clientId: String!) {
        // [4-EXT-1]: 个推SDK已注册，返回clientId
        print("\n>>>[GeTuiSdk RegisterClient]:\(clientId)")
    }
    
    /** SDK遇到错误回调 */
    func geTuiSdkDidOccurError(_ error: Error!) {
        // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
        print("\n>>>[GeTuiSdk error]:\(error.localizedDescription)")
    }
    
    /** SDK收到sendMessage消息回调 */
    func geTuiSdkDidSendMessage(_ messageId: String!, result: Int32) {
        // [4-EXT]:发送上行消息结果反馈
        let msg:String = "sendmessage=\(messageId),result=\(result)"
        print("\n>>>[GeTuiSdk DidSendMessage]:\(msg)")
    }
    
    func geTuiSdkDidReceivePayloadData(_ payloadData: Data!, andTaskId taskId: String!, andMsgId msgId: String!, andOffLine offLine: Bool, fromGtAppId appId: String!) {
        
        var payloadMsg = "";
        print(payloadData)
        if payloadData != nil {
            if let json = try? JSONSerialization.jsonObject(with: payloadData, options: .allowFragments) as AnyObject {
                print("json:",json)
                if json.isKind(of: NSDictionary.classForCoder()) {
                    if json.allKeys.count > 0 {
                        let keyArr = json.allKeys as! [String]
                        if keyArr.contains("body") {
                            let body = json["body"] as! String
                            messageList.append(body)
                            if !offLine {
                                UIApplication.shared.applicationIconBadgeNumber = 0
                                if messageList.count > 0 {
                                    let tmpStr = messageList.last
                                    let customAlert = Bundle.main.loadNibNamed("CustomAlertView", owner: nil, options: nil)?[3] as! CustomAlterView
                                    customAlert.messageLB.text = tmpStr
                                    customAlert.showAlertView()
                                }
                            }
                        }
                        
                    }
                }
            }
            payloadMsg = String.init(data: payloadData, encoding: String.Encoding.utf8)!
        }
        let msg:String = "Payload: \(payloadMsg), taskId:\(taskId), messageId:\(msgId), offLine:\(offLine)";
        print("\n>>>[GeTuiSdk DidReceivePayload]:\(msg)");
    }
}
